package com.bj58.ecdata.dbconnectionpool;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bj58.ecdata.dao.util.PropertiesHelper;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ConnectionPoolFactory
{
	private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolFactory.class);

	/**
	 * @param ph
	 * @param swapDataSource 连接池类型暂时只支持"C3P0"
	 */
	public static synchronized ConnectionPool createPool(PropertiesHelper ph,String swapDataSource)throws Exception
	{
	    SwapConnectionPool dbConnectionPool = new SwapConnectionPool(getC3P0DataSource(ph));
	    return dbConnectionPool;
  }
  
	private static DataSource getC3P0DataSource(PropertiesHelper ph){
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		try {  
			dataSource.setDriverClass(ph.getString("driverClass"));
			dataSource.setJdbcUrl(ph.getString("jdbcUrl"));
			dataSource.setUser(ph.getString("user"));
			dataSource.setPassword(ph.getString("password"));
			dataSource.setMaxPoolSize(ph.getInt("maxPoolSize", 15));
			dataSource.setMinPoolSize(ph.getInt("minPoolSize", 2));
			dataSource.setInitialPoolSize(ph.getInt("initialPoolSize", 2));
			dataSource.setMaxIdleTime(ph.getInt("maxIdleTime", 0));
			dataSource.setMaxIdleTimeExcessConnections(ph.getInt("maxIdleTimeExcessConnections", 0));
			dataSource.setCheckoutTimeout(ph.getInt("checkoutTimeout", 0));
			dataSource.setAcquireIncrement(ph.getInt("acquireIncrement",2));
			dataSource.setAcquireRetryAttempts(ph.getInt("acquireRetryAttempts",5));
			dataSource.setAcquireRetryDelay(ph.getInt("acquireRetryDelay",1000));
			dataSource.setAutoCommitOnClose(ph.getBoolean("autoCommitOnClose",false));
			dataSource.setAutomaticTestTable(ph.getString("automaticTestTable","c3p0TestTable"));
			dataSource.setBreakAfterAcquireFailure(ph.getBoolean("breakAfterAcquireFailure",false));
			dataSource.setIdleConnectionTestPeriod(ph.getInt("idleConnectionTestPeriod",0));
			dataSource.setMaxStatements(ph.getInt("maxStatements",0));
			dataSource.setMaxStatementsPerConnection(ph.getInt("maxStatementsPerConnection",0));
		} catch (Exception e) {
			logger.error("create DataSource error...",e);  
			return null;
		}  
		return dataSource ;
	}

}
